package lan.battletank.element;

import lan.battletank.R;
import lan.battletank.environment.EnvConst;
import lan.battletank.environment.Stage;
import lan.battletank.main.GameStatus;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;

public class PlayerBulletEntity extends BaseBulletElement {

    /** Constructor, initial all parameters here. */
    public PlayerBulletEntity(Context context) {
        super();
        mContext = context;
        Resources res = mContext.getResources();
        mBulletImage = new BitmapDrawable(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(res, R.drawable.bullet_right), 20, 15, true));
        width = mBulletImage.getIntrinsicWidth();
        height = mBulletImage.getIntrinsicHeight();
        halfWidth = width / 2;
        halfHeight = height / 2;
        mExplosion = new ExplosionEntity(context);
    }

    public void action(BaseBattleUnitElement player, BaseBattleUnitElement enemy, Stage stage, IndicatorEntity indicator, int canvasWidth, int canvasHeight, double timeInterval) {
        if (player.isFiring()) {
            if (centerX > canvasWidth + EnvConst.BULLET_OUT_BOUND) {
                // bullet out of the screen, do reset
                reset();
                player.actionEnd();
                indicator.clearFireIndicator();
                GameStatus.setBattleStatus(EnvConst.BATTLE_PLAYER_TURN_END, indicator);
            } else if (mState != STATE_EXPLODING && !shouldExplode(stage, enemy, canvasWidth, canvasHeight)) {
                // flying
                mState = STATE_FLYING;
                bulletSpeedX -= timeInterval * indicator.getWindPower();
                bulletSpeedY -= timeInterval * EnvConst.GRAVITY;
                centerX += timeInterval * bulletSpeedX;
                centerY -= timeInterval * bulletSpeedY;
                bulletTiltAngle = -(float) Math.toDegrees(Math.atan2(bulletSpeedY, bulletSpeedX));
            } else {
                // explosion
                mState = STATE_EXPLODING;
                mExplosion.setExplosion(player, this, enemy, indicator);
            }
        }
    }
}
